package com.imoblife.brainwavestus.obpurchaseSystem;


import java.io.IOException;
import java.net.HttpURLConnection;
import java.net.URL;

import android.app.Dialog;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.TextView;

import com.imoblife.brainwavestus.R;
import com.imoblife.brainwavestus.obpurchaseSystem.OBpurchaseSystem.OBAwardPointsNotifier;
import com.imoblife.brainwavestus.users.UserAccount;
import com.imoblife.brainwavestus.util.DebugUtil;
import com.imoblife.brainwavestus.util.ProductUtil;


public class TusPointManager {

	private final String TAG = "TusPointManager";

	Context mContext;
	EditText mEditText;
	TextView mResultView;
	ImageButton mInput;
	Button mCancal;
	View mInputLayout;
	View mDoingLayout;
	Dialog mDialog;
	Handler mHandler;
	UserAccount user;

	public TusPointManager(Context context) {
		mContext = context;
		mHandler = new Handler();
		mDialog = new Dialog(mContext, android.R.style.Theme_Panel) {

			protected void onStop() {
				mDialog = null;
				super.onStop();
			}

		};
		user = new UserAccount(context);
		mDialog.setContentView(R.layout.get_tus_layout);
		mDialog.show();

		mEditText = (EditText) mDialog.findViewById(R.id.code_tus);
		mInput = (ImageButton) mDialog.findViewById(R.id.input);
		mCancal = (Button) mDialog.findViewById(R.id.cancle);
		mResultView = (TextView) mDialog.findViewById(R.id.result);
		mInputLayout = mDialog.findViewById(R.id.input_layout);
		mDoingLayout = mDialog.findViewById(R.id.doing_layout);
		mInput.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				String codeValue = mEditText.getText().toString();

				codeValue = codeValue.replace(" ", "");

				if (!codeValue.equals("")) {

					new GetTuSPiontTask().execute(codeValue.toLowerCase());
					mInputLayout.setVisibility(View.GONE);
					mDoingLayout.setVisibility(View.VISIBLE);
				}

			}
		});
		mCancal.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {

				mDialog.cancel();

			}
		});

		TextView contactUs = (TextView) mDialog.findViewById(R.id.contact_us);

		contactUs.setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				Intent email = new Intent(android.content.Intent.ACTION_SEND);

				email.putExtra(Intent.EXTRA_EMAIL,
						new String[] { "apple@downloadandroid.info" });

				email.putExtra(Intent.EXTRA_SUBJECT, mContext.getResources()
						.getString(R.string.contact_us_title));

				email.setType("message/rfc822");

				mContext.startActivity(Intent.createChooser(email, mContext
						.getResources().getText(R.string.app_name)));

			}
		});
	}

	class GetTuSPiontTask extends AsyncTask<String, Integer, String> {

		final String url = "http://imoblife.com/register/ixbrainwavestus/tuscoderegister.php?regcode=";

		int state = -1;

		/**
		 * ��̨����
		 */
		protected String doInBackground(final String... params) {

			try {

				URL urlpath = new URL(url + params[0]);
				HttpURLConnection connection = (HttpURLConnection) urlpath
						.openConnection();
				connection.setConnectTimeout(60000);
				connection.connect();

				if (HttpURLConnection.HTTP_OK == connection.getResponseCode()) {

					String result = connection.getHeaderField("rc");

					DebugUtil.debug(TAG, " result = " + result);

					if (result == null) {

						DebugUtil.debug(TAG, "������û�з��ؽ��");

					} else if ("S".equals(result)) {

						state = 0;
						final String tusPoint = connection.getHeaderField("re");
						DebugUtil.debug(TAG, " result  tusPoint= " + tusPoint);
						connection.disconnect();

						if (tusPoint != null) {
							OBpurchaseSystem.getOBpurchaseSystem(mContext)
									.awardTapPoints(Integer.parseInt(tusPoint),
											new OBAwardPointsNotifier() {

												public void getAwardPointsResponse(
														String currencyName,
														final int pointTotal) {

													user.setGold(pointTotal + "");
													mHandler.post(new Runnable() {

														public void run() {
															state = 1;
															onPostExecute(mContext
																	.getResources()
																	.getString(
																			R.string.success)
																	+ " "
																	+ tusPoint
																	+ " "
																	+ mContext
																			.getResources()
																			.getString(
																					R.string._tusadd)
																	+ "\n"
																	+ mContext
																			.getResources()
																			.getString(
																					R.string.tus_total)
																	+ pointTotal);

														}
													});

												}

												public void getAwardPointsResponseFailed(
														String error) {

													mHandler.post(new Runnable() {

														public void run() {
															state = -1;
															onPostExecute(mContext
																	.getResources()
																	.getString(
																			R.string.no_response));

														}
													});

												}

											});

						} else {
						
						}

					} else if ("F".equals(result)) {
						connection.disconnect();
						String re = connection.getHeaderField("re");

						if (re != null && re.equals("Invalid Registration Key")) {

							return mContext.getResources().getString(
									R.string.irk);
						} else {
							DebugUtil.debug(TAG,
									"Invalid Registration Key = null");
						}

					} else {
						
					}

				} else {

				}
				connection.disconnect();
			} catch (IOException e) {

				return mContext.getResources().getString(
						R.string.connect_timeout);
			}

			return mContext.getResources().getString(R.string.no_response);
		}

		/**
		 * UI����ʾ���
		 */
		protected void onPostExecute(String result) {

			DebugUtil.debug(TAG, "result = " + result + " state= " + state);

			if (mDialog != null && state != 0) {

				mDoingLayout.setVisibility(View.GONE);
				mInputLayout.setVisibility(View.VISIBLE);
				mResultView.setVisibility(View.VISIBLE);
				mResultView.setText(result);

				if (state == -1) {
					mResultView.setTextColor(0xffb2a40a);
				} else {
					mResultView.setTextColor(0xff649800);
				}

			}

		}

	}

}
